﻿using MediatR;
using SmartTracking.API.Read.Application.Commands.Permission_command;
using SmartTracking.Domain.UserInfo;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace SmartTracking.API.Read.Application.CommandHandlers.Permission_handler
{
    public class GetPermissionCommandHandler:IRequestHandler<GetPermissionCommand,ApiResult<ApiPaging<Permissions>>>
    {
        private readonly IBaseRepository<Permissions> permissionRep;

        public GetPermissionCommandHandler(
            IBaseRepository<Permissions> permissionRep)
        {
            this.permissionRep = permissionRep;
        }

        public Task<ApiResult<ApiPaging<Permissions>>> Handle(GetPermissionCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<Permissions>> result = new ApiResult<ApiPaging<Permissions>>();
            result.Code = ApiEnum.查询成功;
            result.Message = ApiEnum.查询成功.ToString();

            var list = permissionRep.GetAll().Where(x => x.IsDeleted == false);
            if(!string.IsNullOrEmpty(request.PermissionName))
            {
                list = list.Where(x => x.PermissionName.Equals(request.PermissionName));
            }
            int ListCount = list.Count();
            int PageCount = (int)Math.Ceiling(ListCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(x => x.PermissionId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            ApiPaging<Permissions> paging = new ApiPaging<Permissions>();
            paging.totalCount = ListCount;
            paging.totalPage = PageCount;
            paging.data = list.ToList();

            result.data = paging;
            return Task.FromResult(result);
        }
    }
}
